<script setup>
import { ref, reactive, onMounted } from 'vue'
import { usetikuUserStore } from '@/stores/sj-user'
import request from '@/utils/sj-request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const userStore = usetikuUserStore()
const router = useRouter()

// 用户信息
const userInfo = ref({})

// 表单数据
const userForm = reactive({
  account: '',
})

// 修改邮箱表单
const emailForm = reactive({
  email: '',
  verificationCode: ''
})

// 修改密码表单（通过原密码）
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 修改密码表单（通过验证码）
const passwordWithCodeForm = reactive({
  email: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单规则
const userRules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 20, message: '账号长度必须在4-20个字符之间', trigger: 'blur' }
  ]
}

// 邮箱表单规则
const emailRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 密码表单规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 通过验证码修改密码表单规则
const passwordWithCodeRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordWithCodeForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 表单引用
const userFormRef = ref(null)
const emailFormRef = ref(null)
const passwordFormRef = ref(null)
const passwordWithCodeFormRef = ref(null)

// 加载状态
const userLoading = ref(false)
const emailLoading = ref(false)
const passwordLoading = ref(false)
const passwordWithCodeLoading = ref(false)

// 验证码相关
const sendingEmailCode = ref(false)
const sendingPasswordCode = ref(false)
const emailCountdown = ref(0)
const passwordCountdown = ref(0)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await request({
      url: '/user/info',
      method: 'get'
    })
    userInfo.value = res.data
    userForm.account = userInfo.value.account
    emailForm.email = userInfo.value.email || ''
    passwordWithCodeForm.email = userInfo.value.email || ''
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 更新用户账号
const updateUserInfo = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      // 如果账号没有变化，不需要更新
      if (userForm.account === userInfo.value.account) {
        ElMessage.info('账号未修改')
        return
      }

      // 提示用户7天内只能修改一次
      ElMessageBox.confirm(
        '账号7天内只能修改一次，确定要修改吗？修改后需要重新登录。',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        userLoading.value = true
        try {
          await request({
            url: '/user/info',
            method: 'put',
            data: {
              account: userForm.account
            }
          })
          
          ElMessage.success('账号修改成功，请重新登录')
          // 退出登录
          setTimeout(() => {
            userStore.logout()
            router.push('/login')
          }, 1500)
        } catch (error) {
          console.error('更新账号失败:', error)
          ElMessage.error('更新账号失败')
        } finally {
          userLoading.value = false
        }
      }).catch(() => {
        // 用户取消操作
      })
    }
  })
}

// 发送邮箱验证码
const sendEmailVerificationCode = async () => {
  if (!emailForm.email) {
    ElMessage.warning('请输入新邮箱')
    return
  }
  
  sendingEmailCode.value = true
  try {
    await request({
      url: '/user/email/code',
      method: 'post',
      params: {
        email: emailForm.email
      }
    })
    
    ElMessage.success('验证码已发送到您的邮箱')
    
    // 开始倒计时
    emailCountdown.value = 60
    const timer = setInterval(() => {
      emailCountdown.value--
      if (emailCountdown.value <= 0) {
        clearInterval(timer)
        sendingEmailCode.value = false
      }
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('发送验证码失败')
    sendingEmailCode.value = false
  }
}

// 更新邮箱
const updateEmail = async () => {
  if (!emailFormRef.value) return
  
  await emailFormRef.value.validate(async (valid) => {
    if (valid) {
      // 如果邮箱没有变化，不需要更新
      if (emailForm.email === userInfo.value.email) {
        ElMessage.info('邮箱未修改')
        return
      }

      emailLoading.value = true
      try {
        await request({
          url: '/user/email',
          method: 'put',
          data: {
            email: emailForm.email,
            verificationCode: emailForm.verificationCode
          }
        })
        
        ElMessage.success('邮箱修改成功，请重新登录')
        // 重置表单
        emailForm.verificationCode = ''
        // 退出登录
        setTimeout(() => {
          userStore.logout()
          router.push('/login')
        }, 1500)
      } catch (error) {
        console.error('更新邮箱失败:', error)
        ElMessage.error('更新邮箱失败')
      } finally {
        emailLoading.value = false
      }
    }
  })
}

// 修改密码（通过原密码）
const updatePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        await request({
          url: '/user/password',
          method: 'put',
          data: {
            oldPassword: passwordForm.oldPassword,
            newPassword: passwordForm.newPassword
          }
        })
        
        ElMessage.success('密码修改成功，请重新登录')
        // 重置表单
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
        // 退出登录
        setTimeout(() => {
          userStore.logout()
          router.push('/login')
        }, 1500)
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 发送密码重置验证码
const sendPasswordVerificationCode = async () => {
  sendingPasswordCode.value = true
  try {
    await request({
      url: '/user/password/code',
      method: 'post'
    })
    
    ElMessage.success('验证码已发送到您的邮箱')
    
    // 开始倒计时
    passwordCountdown.value = 60
    const timer = setInterval(() => {
      passwordCountdown.value--
      if (passwordCountdown.value <= 0) {
        clearInterval(timer)
        sendingPasswordCode.value = false
      }
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('发送验证码失败')
    sendingPasswordCode.value = false
  }
}

// 通过验证码修改密码
const updatePasswordWithCode = async () => {
  if (!passwordWithCodeFormRef.value) return
  
  await passwordWithCodeFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordWithCodeLoading.value = true
      try {
        await request({
          url: '/user/password/code',
          method: 'put',
          data: {
            email: passwordWithCodeForm.email,
            verificationCode: passwordWithCodeForm.verificationCode,
            newPassword: passwordWithCodeForm.newPassword
          }
        })
        
        ElMessage.success('密码修改成功，请重新登录')
        // 重置表单
        passwordWithCodeForm.verificationCode = ''
        passwordWithCodeForm.newPassword = ''
        passwordWithCodeForm.confirmPassword = ''
        // 退出登录
        setTimeout(() => {
          userStore.logout()
          router.push('/login')
        }, 1500)
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败')
      } finally {
        passwordWithCodeLoading.value = false
      }
    }
  })
}

// 组件挂载时获取最新用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :span="8">
        <el-card class="user-card" shadow="never">
          <div class="user-avatar">
            <el-avatar :size="100" icon="UserFilled" />
          </div>
          <div class="user-info">
            <h3>{{ userInfo.account || '用户名' }}</h3>
            <p>{{ userInfo.roleName }}</p>
          </div>
          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-value">{{ userInfo.email || '未设置' }}</div>
              <div class="stat-label">邮箱</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 个人信息表单 -->
      <el-col :span="16">
        <el-tabs>
          <el-tab-pane label="修改账号">
            <el-card shadow="never">
              <el-form
                ref="userFormRef"
                :model="userForm"
                :rules="userRules"
                label-width="100px"
              >
                <el-form-item label="当前账号">
                  <el-input v-model="userInfo.account" disabled />
                </el-form-item>
                
                <el-form-item label="新账号" prop="account">
                  <el-input v-model="userForm.account" />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="updateUserInfo" :loading="userLoading">修改账号</el-button>
                  <div class="form-tip">注意：账号7天内只能修改一次，修改后需要重新登录</div>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>
          
          <el-tab-pane label="修改邮箱">
            <el-card shadow="never">
              <el-form
                ref="emailFormRef"
                :model="emailForm"
                :rules="emailRules"
                label-width="100px"
              >
                <el-form-item label="当前邮箱">
                  <el-input v-model="userInfo.email" disabled />
                </el-form-item>
                
                <el-form-item label="新邮箱" prop="email">
                  <el-input v-model="emailForm.email" />
                </el-form-item>
                
                <el-form-item label="验证码" prop="verificationCode">
                  <div class="verification-code-input">
                    <el-input v-model="emailForm.verificationCode" />
                    <el-button 
                      type="primary" 
                      @click="sendEmailVerificationCode" 
                      :disabled="sendingEmailCode" 
                      :loading="sendingEmailCode"
                    >
                      {{ emailCountdown > 0 ? `${emailCountdown}秒后重新获取` : '获取验证码' }}
                    </el-button>
                  </div>
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="updateEmail" :loading="emailLoading">修改邮箱</el-button>
                  <div class="form-tip">注意：修改邮箱后需要重新登录</div>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>
          
          <el-tab-pane label="通过原密码修改密码">
            <el-card shadow="never">
              <el-form
                ref="passwordFormRef"
                :model="passwordForm"
                :rules="passwordRules"
                label-width="100px"
              >
                <el-form-item label="原密码" prop="oldPassword">
                  <el-input v-model="passwordForm.oldPassword" type="password" show-password />
                </el-form-item>
                
                <el-form-item label="新密码" prop="newPassword">
                  <el-input v-model="passwordForm.newPassword" type="password" show-password />
                </el-form-item>
                
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="updatePassword" :loading="passwordLoading">修改密码</el-button>
                  <div class="form-tip">注意：修改密码后需要重新登录</div>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>
          
          <el-tab-pane label="通过验证码修改密码">
            <el-card shadow="never">
              <el-form
                ref="passwordWithCodeFormRef"
                :model="passwordWithCodeForm"
                :rules="passwordWithCodeRules"
                label-width="100px"
              >
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="passwordWithCodeForm.email" disabled />
                </el-form-item>
                
                <el-form-item label="验证码" prop="verificationCode">
                  <div class="verification-code-input">
                    <el-input v-model="passwordWithCodeForm.verificationCode" />
                    <el-button 
                      type="primary" 
                      @click="sendPasswordVerificationCode" 
                      :disabled="sendingPasswordCode" 
                      :loading="sendingPasswordCode"
                    >
                      {{ passwordCountdown > 0 ? `${passwordCountdown}秒后重新获取` : '获取验证码' }}
                    </el-button>
                  </div>
                </el-form-item>
                
                <el-form-item label="新密码" prop="newPassword">
                  <el-input v-model="passwordWithCodeForm.newPassword" type="password" show-password />
                </el-form-item>
                
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input v-model="passwordWithCodeForm.confirmPassword" type="password" show-password />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="updatePasswordWithCode" :loading="passwordWithCodeLoading">修改密码</el-button>
                  <div class="form-tip">注意：修改密码后需要重新登录</div>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.profile-container {
  padding: 20px 0;
}

.user-card {
  text-align: center;
}

.user-avatar {
  margin: 20px 0;
}

.user-info {
  margin-bottom: 20px;
}

.user-info h3 {
  margin: 10px 0 5px;
  font-size: 18px;
}

.user-info p {
  margin: 0;
  color: #909399;
}

.user-stats {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 16px;
  color: #409EFF;
  word-break: break-all;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.verification-code-input {
  display: flex;
}

.verification-code-input .el-input {
  margin-right: 10px;
}

.form-tip {
  font-size: 12px;
  color: #E6A23C;
  margin-top: 5px;
}
</style>